/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cx1.web.controller;

import com.javadocmd.simplelatlng.LatLng;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.cx1.model.Amenity;
import org.cx1.model.Featured;
import org.cx1.model.Place;
import org.cx1.model.Listing;
import org.cx1.model.Listing;
import org.cx1.model.Photo;
import org.cx1.model.User;
import org.cx1.model.deprecated.RETypeL1;
import org.cx1.model.deprecated.RETypeL2;
import org.cx1.model.ds.MockDS;
import org.cx1.model.utils.CXDateUtils;
import org.cx1.model.utils.KPlaceTypeIDs;
import org.cx1.model.utils.ListingComparator;
import org.cx1.model.utils.RateUtils;
import org.cx1.model.utils.SearchOption;
import org.cx1.model.utils.SearchResult;
import org.cx1.model.utils.ServiceResponse;
import org.cx1.model.utils.SystemProperties;
import org.cx1.service.api.IAmenityService;
import org.cx1.service.api.IEmailService;
import org.cx1.service.api.IFeaturedService;
import org.cx1.service.api.IPlaceService;
import org.cx1.service.api.IListingService;
import org.cx1.service.api.IPhotoService;
import org.cx1.service.api.ISearchService;
import org.cx1.service.api.IUserService;
import org.cx1.service.api.deprecated.IRETypeService;
import org.cx1.service.impl.DAmenityService;
import org.cx1.service.impl.DFeaturedService;
import org.cx1.service.impl.DListingService;
import org.cx1.service.impl.DPhotoService;
import org.cx1.service.impl.DPlaceService;
import org.cx1.service.impl.DUserService;
import org.cx1.service.impl.MAmenityService;
import org.cx1.service.impl.MEmailService;
import org.cx1.service.impl.MPlaceService;
import org.cx1.service.impl.MListingService;
import org.cx1.service.impl.MPhotoService;
import org.cx1.service.impl.MSearchService;
import org.cx1.service.impl.MUserService;
import org.cx1.service.impl.deprecated.RETypeService;
import org.cx1.service.utils.IDGenerator;
import org.cx1.service.utils.ImageProcessor;
import org.cx1.service.utils.UAgentInfo;
import org.cx1.web.controller.action.ListingAction;
import org.cx1.web.utils.SessionUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.view.RedirectView;

/**
 *
 * @author ECH
 */
public class ListingController extends BaseController {
    
    //private IListingService listingService = new MListingService();
    //private IPlaceService placeService = new MPlaceService();
    //private IPhotoService photoService = new MPhotoService();
    //private IAmenityService amenityService = new MAmenityService();
    //private IUserService userService = new MUserService();
    
    private IListingService listingService = new DListingService();
    private IPlaceService placeService = new DPlaceService();
    private IPhotoService photoService = new DPhotoService();
    private IAmenityService amenityService = new DAmenityService();    
    private IUserService userService = new DUserService();
    
    private IEmailService emailService = new MEmailService();
    
    public ListingController() {
    }

    protected ModelAndView handleRequestInternal( HttpServletRequest request,
                                                  HttpServletResponse response) throws Exception {        
        ModelAndView mav = new ModelAndView();
        Map map = new HashMap();        
        
        boolean loggedin = false;
        String userID = SessionUtils.getUserID(request.getSession());   
        
        System.out.println("CX: " + request.getSession().getId());
        System.out.println("CX: req- " + request.getRequestedSessionId());
        
        if (!StringUtils.isEmpty(userID)) {
            loggedin = true;
            map.put("loggedin", loggedin);
        }
        
        Map<String, Object> parameterMap = new HashMap<String, Object>();
        if (ServletFileUpload.isMultipartContent(request)) {
            parameterMap = this.getMultipartFormParams(request);
        }  
       else {
            parameterMap = this.getFormParams(request);
        }
        
        Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields");
        int action = StringUtils.isEmpty(formfields.get("a")) ? 0 : Integer.parseInt(formfields.get("a"));
        
        switch (action) {
            case ListingAction.READ_ALL: {
                readAll(mav, map, request);
                break;
            }                
            case ListingAction.READ: {
                read(userID, mav, map, request);
                break;
            }
            case ListingAction.CREATE: {                      
                if (loggedin) {
                    create(userID, mav, map, request);         
                }
                else {
                    mav.setView(new RedirectView("login.htm"));
                    return mav;                    
                }
                break;
            }
            case ListingAction.UPDATE: {                      
                if (loggedin) {
                    update(userID, mav, map, request);         
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }    
            case ListingAction.DELETE: {                      
                if (loggedin) {
                    delete(userID, mav, map, request);         
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
            case ListingAction.CREATE_PHOTO: {                      
                if (loggedin) {
                    createPhoto(userID, mav, map, request, parameterMap);        
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
            case ListingAction.DELETE_PHOTO: {                      
                if (loggedin) {
                    deletePhoto(userID, mav, map, request, parameterMap);        
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }       
            case ListingAction.UPDATE_PHOTO: {                      
                if (loggedin) {
                    updatePhoto(userID, mav, map, request, parameterMap);        
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
                
            case ListingAction.READ_ALL_MANAGE: {                      
                if (loggedin) {
                    readAll_manage(mav, map, request);          
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
            case ListingAction.READ_MANAGE: {                      
                if (loggedin) {
                    read_manage(mav, map, request);          
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
            case ListingAction.CREATE_MANAGE: {                      
                if (loggedin) {
                    create_manage(userID, mav, map, request);       
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
            case ListingAction.UPDATE_MANAGE: {                      
                if (loggedin) {
                    update_manage(mav, map, request);         
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
            case ListingAction.DELETE_MANAGE: {                      
                if (loggedin) {
                    delete_manage(mav, map, request);          
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
            
            case ListingAction.CREATE_PHOTO_MANAGE: {                      
                if (loggedin) {
                    createPhoto_manage(mav, map, request, parameterMap);   
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
            case ListingAction.DELETE_PHOTO_MANAGE: {                      
                if (loggedin) {
                    deletePhoto_manage(mav, map, request, parameterMap);          
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }  
            case ListingAction.UPDATE_PHOTO_MANAGE: {                      
                if (loggedin) {
                    updatePhoto_manage(mav, map, request, map);         
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }                    
                
            case ListingAction.SET_AVAILABLE: {                      
                if (loggedin) {
                    setListingAvailable(mav, map, request, map);         
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }    
            case ListingAction.SET_UNAVAILABLE: {                                   
                if (loggedin) {
                setListingUnavailable(mav, map, request, map);         
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;  
            }
            case ListingAction.SET_AVAILABLE_LINK: {      
                setListingAvailableLink(mav, map, request, map); 
                break;
            }    
            case ListingAction.SET_UNAVAILABLE_LINK: {   
                setListingUnavailableLink(mav, map, request, map);  
                break;
            }    
                
                
                
            case ListingAction.POST_LISTING: {                      
                if (loggedin) {
                    postListing(mav, map, request, map);         
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            } 
            case ListingAction.UNPOST_LISTING: {                      
                if (loggedin) {
                    unpostListing(mav, map, request, map);     
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }  
            case ListingAction.PENALIZE_LISTING: {                      
                if (loggedin) {
                    penalizeListing(mav, map, request, map);     
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }  
            case ListingAction.READ_ALL_LONG_TERM_LIST: {
                readAllLongTermList(mav, map, request);
                break;
            }  
            case ListingAction.READ_ALL_SHORT_TERM_LIST: {
                readAllShortTermList(mav, map, request);
                break;
            }      
            case ListingAction.SHARE_LISTING: {
                shareListing(mav, map, request);
                break;
            }
            case ListingAction.MAP_LISTING: {
                mapListing(mav, map, request);
                break;
            }
            case ListingAction.EMAIL_LISTING_APPROVED: {
                emalListingApproved(mav, map, request);
                break;
            }
            case ListingAction.EMAIL_LISTING_REJECTED: {
                emalListingRejected(mav, map, request);
                break;
            }
            case ListingAction.EMAIL_LISTING_FEATURED: {
                emalListingFeatured(mav, map, request);
                break;
            }
            case ListingAction.EMAIL_LISTING_BOOST: {
                emalListingBoost(mav, map, request);
                break;
            }   
            case ListingAction.EMAIL_LISTING_ENDED: {
                emalListingEnded(mav, map, request);
                break;
            }   
            default: {
                readAll(mav, map, request);
                break;
            }
        }          
                
        map.put("host", SystemProperties.SYSTEM_HOST);
        map.put("port", SystemProperties.SYSTEM_PORT);
        map.put("props", this.getSystemProperties());
        
        mav.addObject("model", map);
        return mav;
    }

    private void readAll(ModelAndView mav, Map map, HttpServletRequest request) {
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        ServiceResponse<List<Listing>> response = listingService.readAllVerified(StringUtils.isEmpty(offset) ? 0 : Integer.parseInt(offset), StringUtils.isEmpty(limit) ? 0 : Integer.parseInt(limit), true);
        map.put("listings", response.getResponse());
        mav.setViewName("listings");
    }
        
    private void readAllLongTermList(ModelAndView mav, Map map, HttpServletRequest request) {
        ServiceResponse<List<Listing>> response = listingService.readAllPosted(0, 0, true, 1);
        map.put("listings", response.getResponse());
        mav.setViewName("listings_longtermlist");
    }
    
    private void readAllShortTermList(ModelAndView mav, Map map, HttpServletRequest request) {
        ServiceResponse<List<Listing>> response = listingService.readAllPosted(0, 0, true, 2);
        map.put("listings", response.getResponse());
        mav.setViewName("listings_shorttermlist");
    }
    
    private void read(String userID, ModelAndView mav, Map map, HttpServletRequest request) {
        try {
            String id = request.getParameter("id");
            String strLeaseTermType = request.getParameter("leaseTermType");
            int leaseTermType = StringUtils.isEmpty(strLeaseTermType) ? 1 : Integer.parseInt(strLeaseTermType);    
            
            boolean owner = false;
            ServiceResponse<Listing> response = listingService.read(id);

            //CX: check if owner
            if (response.isSuccessful() && response.getResponse() != null) {
                Listing listing = response.getResponse();
                if (!StringUtils.isEmpty(listing.getCreatorID()) && StringUtils.equalsIgnoreCase(listing.getCreatorID(), userID)) {
                    owner = true;
                }
                
                //CX: increment views
                listingService.incrementViews(id);
                
                //CX: increment place impressions
                //if (response.getResponse().getPlaceIDs() != null && response.getResponse().getPlaceIDs().size() > 0) {
                //    for (String placeID : response.getResponse().getPlaceIDs()) {
                //        placeService.incrementImpressions(placeID);
                //    }
                //}
            }

            Listing listing = response.getResponse();
            Set<Listing> similarListings = new HashSet<Listing>();   

            if (listing != null) {
                //CX: set least term type
                if (leaseTermType == 0) {
                    if (listing.isLeaseLongTerm()) {
                        leaseTermType = 1;
                    }
                    else {
                        leaseTermType = 2;
                    }
                }
                
                
                HttpSession session = request.getSession();
                //session.invalidate();
                //session = request.getSession(true);
                //SessionUtils.setUserID(userID, session);
                
                String at = IDGenerator.generateID();
                session.setAttribute("at", at);
                map.put("at", at);
                
                Listing listing1 = fixListingData(response.getResponse());
                String ownerID = "";
                try { ownerID = new StringBuilder().append(listing1.getCreatorID()).reverse().toString(); } catch (Exception ex) { }
                
                map.put("listing", listing1);
                map.put("leaseTermType", leaseTermType);
                map.put("listings", similarListings);   
                map.put("owner", owner);
                map.put("ownerID", ownerID);
                
                if (this.isThisRequestCommingFromAMobileDevice(request)) {
                    mav.setViewName("listing_mobile");
                } 
                else {
                    mav.setViewName("listing");
                }
            }
            else {
                mav.setView(new RedirectView("home.htm"));           
            }
        }
        catch (Exception ex) {             
            mav.setView(new RedirectView("home.htm"));   
        }        
    }
    
    public static int randInt(int min, int max) {
        Random rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;
        return randomNum;
    }
    
    private void create(String userID, ModelAndView mav, Map map, HttpServletRequest request) {
                
        if (StringUtils.isEmpty(userID)) {
            mav.setView( new RedirectView("login.htm") );
            return;
        }
        
        if (!StringUtils.isEmpty(request.getParameter("s"))) {
                        
            String leaseLongTerm = request.getParameter("leaseLongTerm");
            String leaseShortTerm = request.getParameter("leaseShortTerm");
            
            String longMonthRate = request.getParameter("longMonthRate");            
            String shortDayRate = request.getParameter("shortDayRate");
            String shortWeekRate = request.getParameter("shortWeekRate");
            String shortMonthRate = request.getParameter("shortMonthRate"); 
            
            String propertyTypeID = request.getParameter("propertyTypeID");            
            String statusTypeID = request.getParameter("statusTypeID");           
            String posterTypeID = request.getParameter("posterTypeID");        
            String furnishTypeID = request.getParameter("furnishTypeID");
    
            String title = request.getParameter("title");
            String description = request.getParameter("description");
            String notes = request.getParameter("notes");
            
            String address = request.getParameter("address");
            String country = request.getParameter("country");
            String region = request.getParameter("region");
            String city = request.getParameter("city");
            String barangay = request.getParameter("barangay");
            String street = request.getParameter("street");
            String structure = request.getParameter("structure");
            String number = request.getParameter("number");
            String floor = request.getParameter("floor");
            String zip = request.getParameter("zip");
                        
            String lat = request.getParameter("lat");
            String lng = request.getParameter("lng");
            String sqArea = request.getParameter("sqArea");
              
            String numBedrooms = request.getParameter("numBedrooms");
            String numBathrooms = request.getParameter("numBathrooms");
                    
            String availabilityDate = request.getParameter("availabilityDate"); 
            String expiryDate = request.getParameter("expiryDate"); 
            
            String available = request.getParameter("available");
                
            String primaryPhotoID = request.getParameter("primaryPhotoID");
            String photoIDs = request.getParameter("photoIDs");
            
            String placeIDs = request.getParameter("placeIDs");
            String amenityIDs = request.getParameter("amenityIDs");
            
            String contactPersonIDs = request.getParameter("contactPersonIDs");
            String companyIDs = request.getParameter("companyIDs");
            
                        
            Listing listing = new Listing();   
                        
            listing.setLeaseLongTerm(StringUtils.isEmpty(leaseLongTerm) ? false : true);
            listing.setLeaseShortTerm(StringUtils.isEmpty(leaseShortTerm) ? false : true);
            
            listing.setLongMonthRate(longMonthRate);            
            listing.setShortDayRate(shortDayRate);
            listing.setShortWeekRate(shortWeekRate);
            listing.setShortMonthRate(shortMonthRate);
            
            listing.setLongMonthRateNum(RateUtils.strRateToNum(longMonthRate));
            listing.setShortMonthRateNum(RateUtils.strRateToNum(shortMonthRate));
            listing.setShortWeekRateNum(RateUtils.strRateToNum(shortWeekRate));
            listing.setShortDayRateNum(RateUtils.strRateToNum(shortDayRate));
            
            listing.setPropertyTypeID(propertyTypeID);            
            listing.setStatusTypeID(statusTypeID);
            listing.setPosterTypeID(posterTypeID);
                                    
            listing.setTitle(title);
            listing.setDescription(StringUtils.isEmpty(description) ? "" : description.trim());
            listing.setNotes(notes);
            
            listing.setAddress(address);
            listing.setCountry(country);
            listing.setRegion(region);
            listing.setCity(city);
            listing.setBarangay(barangay);
            listing.setStreet(street);
            listing.setStructure(structure);
            listing.setNumber(number);
            listing.setFloor(floor);
            listing.setZip(zip);
            
            listing.setLat(lat);
            listing.setLng(lng);
                     
            try { listing.setSqArea(StringUtils.isEmpty(sqArea) ? 0 : Double.parseDouble(sqArea)); } catch (Exception ex) { }
            try { listing.setNumBedrooms(StringUtils.isEmpty(numBedrooms) ? 0 : Integer.parseInt(numBedrooms) ); } catch (Exception ex) { }
            try { listing.setNumBathrooms(StringUtils.isEmpty(numBathrooms) ? 0 : Integer.parseInt(numBathrooms) ); } catch (Exception ex) { }
                                 
            listing.setFurnishTypeID(furnishTypeID);
            
            //CX: startdate here
            //CX: enddate here
            listing.setAvailable(StringUtils.isEmpty(available) ? false : true);
            listing.setAvailabilityDate(StringUtils.isEmpty(availabilityDate) ? null : CXDateUtils.parseSDF1(availabilityDate));   
            listing.setExpiryDate(StringUtils.isEmpty(expiryDate) ? null : CXDateUtils.parseSDF1(expiryDate));   
                        
            listing.setPrimaryPhotoID(primaryPhotoID);
            listing.setPhotoIDs(StringUtils.isEmpty(photoIDs) ? new ArrayList<String>() : Arrays.asList(photoIDs.split("\\s*,\\s*")));
            
            listing.setPlaceIDs(StringUtils.isEmpty(placeIDs) ? new ArrayList<String>() : Arrays.asList(placeIDs.split("\\s*,\\s*")));
            listing.setAmenityIDs(StringUtils.isEmpty(amenityIDs) ? new ArrayList<String>() : Arrays.asList(amenityIDs.split("\\s*,\\s*")));
                
            listing.setContactPersonIDs(StringUtils.isEmpty(contactPersonIDs) ? new ArrayList<String>() : Arrays.asList(contactPersonIDs.split("\\s*,\\s*")));
            listing.setCompanyIDs(StringUtils.isEmpty(companyIDs) ? new ArrayList<String>() : Arrays.asList(companyIDs.split("\\s*,\\s*")));
                                    
            //CX: set creator
            listing.setCreatorID(userID);
            
            //CX: populate building, village and district
            populateListingPlaces(listing);
            
            ServiceResponse<String> response = listingService.create(listing);
            map.put("listing", response.getResponse());
            
            //CX: send email confirmation
            if (!StringUtils.isEmpty(response.getResponse())) {
                ServiceResponse<User> response1 = userService.read(userID);
                
                if (response1.isSuccessful() && response1.getResponse() != null) {
                    User user = response1.getResponse();
                    StringBuilder strBuilder = new StringBuilder();
                    
                    if (!StringUtils.isEmpty(user.getFirstName())) {
                        strBuilder.append(user.getFirstName());              
                    }
                    //emailService.sendPostListingConfirmation(title, strBuilder.toString(), user.getEmail());                    
                }
            }
            
            //mav.setView(new RedirectView("listing.htm?a="+ListingAction.READ+"&id="+response.getResponse()));  
            mav.setView(new RedirectView("listing.htm?a="+ListingAction.UPDATE_PHOTO+"&id="+response.getResponse()));  
        }
        else {
            ServiceResponse<List<Place>> response2 = placeService.readAll(0, 0);
            map.put("places", response2.getResponse());            
            map.put("amenities", amenityService.readAll(0, 0).getResponse());            
            
            if (isThisRequestCommingFromAMobileDevice(request)) {
                mav.setViewName("listingadd_mobile");
            }
            else {
                mav.setViewName("listingadd");                       
            }
        }
    }
    
    private void update(String userID, ModelAndView mav, Map map, HttpServletRequest request) {
        if (!StringUtils.isEmpty(request.getParameter("s"))) {            
            String id = request.getParameter("id");
            
            String leaseLongTerm = request.getParameter("leaseLongTerm");
            String leaseShortTerm = request.getParameter("leaseShortTerm");
            
            String longMonthRate = request.getParameter("longMonthRate");            
            String shortDayRate = request.getParameter("shortDayRate");
            String shortWeekRate = request.getParameter("shortWeekRate");
            String shortMonthRate = request.getParameter("shortMonthRate");
            
            String propertyTypeID = request.getParameter("propertyTypeID");
            String statusTypeID = request.getParameter("statusTypeID");
            String posterTypeID = request.getParameter("posterTypeID");
            String furnishTypeID = request.getParameter("furnishTypeID");
            
            String title = request.getParameter("title");
            String description = request.getParameter("description");
            String notes = request.getParameter("notes");
            
            String address = request.getParameter("address");
            String country = request.getParameter("country");
            String region = request.getParameter("region");
            String city = request.getParameter("city");
            String barangay = request.getParameter("barangay");
            String street = request.getParameter("street");
            String structure = request.getParameter("structure");
            String number = request.getParameter("number");
            String floor = request.getParameter("floor");
            String zip = request.getParameter("zip");
                                 
            String sqArea = request.getParameter("sqArea");
            
            String dayRate = request.getParameter("dayRate");
            String weekRate = request.getParameter("weekRate");
            String monthRate = request.getParameter("monthRate");
            String yearRate = request.getParameter("yearRate");
            
            String numBedrooms = request.getParameter("numBedrooms");
            String numBathrooms = request.getParameter("numBathrooms");
            
            String leaseStartDate = request.getParameter("leaseStartDate");
            String leaseEndDate = request.getParameter("leaseEndDate");
            String availabilityDate = request.getParameter("availabilityDate");   
            String expiryDate = request.getParameter("expiryDate"); 
            
            String available = request.getParameter("available");  
            
            String primaryPhotoID = request.getParameter("primaryPhotoID");
            String photoIDs = request.getParameter("photoIDs");
            
            String amenityIDs = request.getParameter("amenityIDs");
            
            
            ServiceResponse<Listing> response1 = listingService.read(id);              
            Listing listing = response1.getResponse();          
            
            if (listing != null) {
                
                listing.setLeaseLongTerm(StringUtils.isEmpty(leaseLongTerm) ? false : true);
                listing.setLeaseShortTerm(StringUtils.isEmpty(leaseShortTerm) ? false : true);

                listing.setLongMonthRate(longMonthRate);            
                listing.setShortDayRate(shortDayRate);
                listing.setShortWeekRate(shortWeekRate);
                listing.setShortMonthRate(shortMonthRate);
                            
                listing.setLongMonthRateNum(RateUtils.strRateToNum(longMonthRate));
                listing.setShortMonthRateNum(RateUtils.strRateToNum(shortMonthRate));
                listing.setShortWeekRateNum(RateUtils.strRateToNum(shortWeekRate));
                listing.setShortDayRateNum(RateUtils.strRateToNum(shortDayRate));
            
                listing.setPropertyTypeID(propertyTypeID);
                listing.setStatusTypeID(statusTypeID);
                listing.setPosterTypeID(posterTypeID);
                listing.setFurnishTypeID(furnishTypeID);
                
                listing.setTitle(title);
                listing.setDescription(StringUtils.isEmpty(description) ? "" : description.trim());
                listing.setNotes(notes);

                listing.setAddress(address);
                listing.setCountry(country);
                listing.setRegion(region);
                listing.setCity(city);
                listing.setBarangay(barangay);
                listing.setStreet(street);
                listing.setStructure(structure);
                listing.setNumber(number);
                listing.setFloor(floor);
                listing.setZip(zip);
                            
                listing.setSqArea(StringUtils.isEmpty(sqArea) ? 0 : Double.parseDouble(sqArea));
            
                listing.setDayRate(dayRate);
                listing.setWeekRate(weekRate);
                listing.setMonthRate(monthRate);
                listing.setYearRate(yearRate);

                listing.setNumBedrooms(StringUtils.isEmpty(numBedrooms) ? 0 : Integer.parseInt(numBedrooms) );
                listing.setNumBathrooms(StringUtils.isEmpty(numBathrooms) ? 0 : Integer.parseInt(numBathrooms) );
                
                //CX: startdate here
                //CX: enddate here
                listing.setAvailabilityDate(StringUtils.isEmpty(availabilityDate) ? null : CXDateUtils.parseSDF1(availabilityDate));
                
                listing.setAvailable(StringUtils.isEmpty(available) ? false : true); 
                listing.setExpiryDate(StringUtils.isEmpty(expiryDate) ? null : CXDateUtils.parseSDF1(expiryDate));   

                listing.setAmenityIDs(StringUtils.isEmpty(amenityIDs) ? null : Arrays.asList(amenityIDs.split("\\s*,\\s*")));
                
                
                ServiceResponse<Boolean> response = listingService.update(listing);
                map.put("listing", response.getResponse());
                mav.setView(new RedirectView("listing.htm?a="+ListingAction.READ+"&id="+id));
            }
            else {
                mav.setView(new RedirectView("listing.htm"));                
            }
        }        
        else {               
            String id = request.getParameter("id");
            ServiceResponse<Listing> response1 = listingService.read(id); 
            Listing listing = response1.getResponse();
            
            if (listing != null && StringUtils.equalsIgnoreCase(userID, listing.getCreatorID())) {
                ServiceResponse<List<Place>> response2 = placeService.readAll(0, 0);
                ServiceResponse<List<Amenity>> response3 = amenityService.readAll(0, 0);

                map.put("listing", response1.getResponse());
                map.put("places", response2.getResponse());
                map.put("amenities", response3.getResponse()); 
                
                if (isThisRequestCommingFromAMobileDevice(request)) {
                    mav.setViewName("listingedit_mobile");  
                }
                else {
                    mav.setViewName("listingedit");                       
                }      
                
            }
            else {
                mav.setView(new RedirectView("home.htm"));
            }
        }
    }
    
    private void delete(String userID, ModelAndView mav, Map map, HttpServletRequest request) {
        String listingID = request.getParameter("id");
        ServiceResponse<Boolean> response = listingService.delete(listingID, userID);        
        mav.setView(new RedirectView("account.htm"));
    }
    
    private void createPhoto(String userID, ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {        
        Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields");
        List<Photo> photos = new ArrayList<Photo>();
        
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);       
        String listingID = formfields.get("id"); 
        
        ServiceResponse<Listing> response2 = listingService.read(listingID);
        Listing listing = response2.getResponse();
        if (listing != null && StringUtils.equalsIgnoreCase(listing.getCreatorID(), userID)) {        
            try {
                if (isMultipart) {
                    List filefields = (List) parameterMap.get("filefields");
                    Iterator iterator = filefields.iterator();

                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();

                        if (!item.isFormField()) {
                            String fileName = item.getName();

                            if (!StringUtils.isEmpty(fileName)) {
                                String ext = "";

                                if (StringUtils.containsIgnoreCase(fileName, ".jpg") || StringUtils.containsIgnoreCase(fileName, ".jpeg")) {
                                    ext = ".jpg";
                                }
                                if (StringUtils.containsIgnoreCase(fileName, ".png")) {
                                    ext = ".png";
                                }

                                String genFileName = UUID.randomUUID().toString();                        
                                fileName = genFileName;
                                fileName = fileName + ext;

                                String root = getServletContext().getRealPath("/");
                                root = SystemProperties.PHOTO_DIRECTORY;
                                File path = new File(root);

                                if (!path.exists()) {
                                    boolean status = path.mkdirs();
                                }
                                File uploadedFile = new File(path + "/" + fileName );

                                if (!uploadedFile.exists()) {
                                    //CX: write photo
                                    item.write(uploadedFile);
                                    //CX: write standard and preview sizes
                                    ImageProcessor proc = new ImageProcessor();
                                    proc.createStandardSize(uploadedFile);
                                    proc.createPreviewSize(uploadedFile);
                                }
                                photos.add(new Photo(root, fileName));
                            }
                        }
                    }
                }

                if (formfields != null && !StringUtils.isEmpty((String) formfields.get("s"))) {                
                    if (photos != null && photos.size() > 0) {
                        for (Photo photo : photos) {
                            ServiceResponse<String> response1 = photoService.createListingPhoto(listingID, photo);   
                            Thread.sleep(1100);
                        }                    
                    }
                }            
            } 
            catch (Exception ex) {
                ex.printStackTrace();
            }    
            mav.setView(new RedirectView("listing.htm?a="+ListingAction.UPDATE_PHOTO+"&id="+listingID));
        }   
        else {
            mav.setView(new RedirectView("home.htm"));
        }
    }   
    
    private void deletePhoto(String userID, ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {
        String listingID = request.getParameter("listingID");
        String photoID = request.getParameter("photoID");
        
        ServiceResponse<Listing> response1 = listingService.read(listingID);
        Listing listing = response1.getResponse();        
        if (listing != null && StringUtils.equalsIgnoreCase(listing.getCreatorID(), userID)) {
            ServiceResponse<Boolean> response = photoService.deleteListingPhoto(listingID, photoID, userID); 
            mav.setView(new RedirectView("listing.htm?a="+ListingAction.UPDATE_PHOTO+"&id="+listingID));            
        }
        else {
            mav.setView(new RedirectView("home.htm"));
        }
    }
    
    //CX: management functions
    
    private void readAll_manage(ModelAndView mav, Map map, HttpServletRequest request) {
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        
        if (StringUtils.isEmpty(limit)) {
            limit = "30";
        }
        
        ServiceResponse<List<Listing>> response = listingService.readAll(StringUtils.isEmpty(offset) ? 0 : Integer.parseInt(offset), StringUtils.isEmpty(limit) ? 0 : Integer.parseInt(limit));
        List<Listing> listings = response.getResponse();       
        
        map.put("listings", listings);
        mav.setViewName("listings_manage");
    }
        
    private void read_manage(ModelAndView mav, Map map, HttpServletRequest request) {
        String id = request.getParameter("id");
        ServiceResponse<Listing> response = listingService.read(id);
        map.put("listing", response.getResponse());
        mav.setViewName("listing_manage");
    }
    
    private void create_manage(String userID, ModelAndView mav, Map map, HttpServletRequest request) {
        if (!StringUtils.isEmpty(request.getParameter("s"))) {            
            //CX: retrieve parameters            
            String leaseLongTerm = request.getParameter("leaseLongTerm");
            String leaseShortTerm = request.getParameter("leaseShortTerm");
            
            String longMonthRate = request.getParameter("longMonthRate");            
            String shortDayRate = request.getParameter("shortDayRate");
            String shortWeekRate = request.getParameter("shortWeekRate");
            String shortMonthRate = request.getParameter("shortMonthRate");
            
            String propertyTypeID = request.getParameter("propertyTypeID");
            String statusTypeID = request.getParameter("statusTypeID");
            String posterTypeID = request.getParameter("posterTypeID");
            String furnishTypeID = request.getParameter("furnishTypeID");
    
            String title = request.getParameter("title");
            String description = request.getParameter("description");
            String notes = request.getParameter("notes");
            
            String address = request.getParameter("address");
            
            String number = request.getParameter("number");
            String floor = request.getParameter("floor");
            String structure = request.getParameter("structure");
            String street = request.getParameter("street");
            String barangay = request.getParameter("barangay");
            String city = request.getParameter("city");
            String region = request.getParameter("region");
            String country = request.getParameter("country");
            
            String zip = request.getParameter("zip");
                        
            String lat = request.getParameter("lat");
            String lng = request.getParameter("lng");
            
            String sqArea = request.getParameter("sqArea");    
            String numBedrooms = request.getParameter("numBedrooms");
            String numBathrooms = request.getParameter("numBathrooms");
            String amenityIDs = request.getParameter("amenityIDs");
                        
            String monthRate = request.getParameter("monthRate");                 
            String sellingPrice = request.getParameter("sellingPrice");
            
            String availabilityDate = request.getParameter("availabilityDate"); 
            
            String placeIDs = request.getParameter("placeIDs");
            
            String expiryDate = request.getParameter("expiryDate");             
            String verified = request.getParameter("verified");              
            String creatorID = request.getParameter("creatorID");           
                        
            //CX: assign to listing attributes
            Listing listing = new Listing();   
            
            listing.setLeaseLongTerm(StringUtils.isEmpty(leaseLongTerm) ? false : true);
            listing.setLeaseShortTerm(StringUtils.isEmpty(leaseShortTerm) ? false : true);
            
            listing.setLongMonthRate(longMonthRate);            
            listing.setShortDayRate(shortDayRate);
            listing.setShortWeekRate(shortWeekRate);
            listing.setShortMonthRate(shortMonthRate);
                        
            listing.setLongMonthRateNum(RateUtils.strRateToNum(longMonthRate));
            listing.setShortMonthRateNum(RateUtils.strRateToNum(shortMonthRate));
            listing.setShortWeekRateNum(RateUtils.strRateToNum(shortWeekRate));
            listing.setShortDayRateNum(RateUtils.strRateToNum(shortDayRate));
            
            listing.setPropertyTypeID(propertyTypeID);
            listing.setStatusTypeID(statusTypeID);
            listing.setPosterTypeID(posterTypeID);
            listing.setFurnishTypeID(furnishTypeID);
            
            listing.setTitle(title);
            listing.setDescription(StringUtils.isEmpty(description) ? "" : description.trim());
            listing.setNotes(notes);
            
            listing.setAddress(address);
            
            listing.setCountry(country);
            listing.setRegion(region);
            listing.setCity(city);
            listing.setBarangay(barangay);
            listing.setStreet(street);
            listing.setStructure(structure);
            listing.setNumber(number);
            listing.setFloor(floor);
            listing.setZip(zip);            
            listing.setLat(lat);
            listing.setLng(lng);
                     
            listing.setSqArea(StringUtils.isEmpty(sqArea) ? 0 : Double.parseDouble(sqArea));
            listing.setNumBedrooms(StringUtils.isEmpty(numBedrooms) ? 0 : Integer.parseInt(numBedrooms) );
            listing.setNumBathrooms(StringUtils.isEmpty(numBathrooms) ? 0 : Integer.parseInt(numBathrooms) );
            listing.setAmenityIDs(StringUtils.isEmpty(amenityIDs) ? null : Arrays.asList(amenityIDs.split("\\s*,\\s*")));
            
            listing.setMonthRate(monthRate);
            listing.setSellingPrice(sellingPrice);
            
            listing.setAvailabilityDate(StringUtils.isEmpty(availabilityDate) ? null : CXDateUtils.parseSDF1(availabilityDate));  

            listing.setPlaceIDs(StringUtils.isEmpty(placeIDs) ? null : Arrays.asList(placeIDs.split("\\s*,\\s*")));
                            
            listing.setVerified(StringUtils.isEmpty(verified) ? false : true);
            
            listing.setExpiryDate(StringUtils.isEmpty(expiryDate) ? null : CXDateUtils.parseSDF1(expiryDate));  
            
            //CX: set creator
            listing.setCreatorID(creatorID); 
                                                
            //CX: populate building, village and district
            populateListingPlaces(listing);
            
            ServiceResponse<String> response = listingService.create(listing);
            map.put("listing", response.getResponse());
            //mav.setView(new RedirectView("listing.htm?a="+ListingAction.READ_MANAGE+"&id="+response.getResponse()));  
            
            mav.setView(new RedirectView("listing.htm?a="+ListingAction.UPDATE_PHOTO_MANAGE+"&id="+response.getResponse())); 
        }
        else {
            ServiceResponse<List<Place>> response2 = placeService.readAll(0, 0);
            ServiceResponse<List<Amenity>> response3 = amenityService.readAll(0, 0);
            
            map.put("places", response2.getResponse());
            map.put("amenities", response3.getResponse());            
            mav.setViewName("listingadd_manage");
        }
    }
        
    private void update_manage(ModelAndView mav, Map map, HttpServletRequest request) {
        if (!StringUtils.isEmpty(request.getParameter("s"))) {            
            String id = request.getParameter("id");
            
            String leaseLongTerm = request.getParameter("leaseLongTerm");
            String leaseShortTerm = request.getParameter("leaseShortTerm");
            
            String longMonthRate = request.getParameter("longMonthRate");            
            String shortDayRate = request.getParameter("shortDayRate");
            String shortWeekRate = request.getParameter("shortWeekRate");
            String shortMonthRate = request.getParameter("shortMonthRate");
            
            String propertyTypeID = request.getParameter("propertyTypeID");
            String statusTypeID = request.getParameter("statusTypeID");
            String posterTypeID = request.getParameter("posterTypeID");
            String furnishTypeID = request.getParameter("furnishTypeID");
    
            String title = request.getParameter("title");
            String description = request.getParameter("description");
            String notes = request.getParameter("notes");
            
            String address = request.getParameter("address");
            
            String number = request.getParameter("number");
            String floor = request.getParameter("floor");
            String structure = request.getParameter("structure");
            String street = request.getParameter("street");
            String barangay = request.getParameter("barangay");
            String city = request.getParameter("city");
            String region = request.getParameter("region");
            String country = request.getParameter("country");
            
            String zip = request.getParameter("zip");
                        
            String lat = request.getParameter("lat");
            String lng = request.getParameter("lng");
            
            String sqArea = request.getParameter("sqArea");    
            String numBedrooms = request.getParameter("numBedrooms");
            String numBathrooms = request.getParameter("numBathrooms");
            String amenityIDs = request.getParameter("amenityIDs");
                        
            String monthRate = request.getParameter("monthRate");     
            String sellingPrice = request.getParameter("sellingPrice");
            
            String availabilityDate = request.getParameter("availabilityDate"); 
            
            String placeIDs = request.getParameter("placeIDs");
                        
            String verified = request.getParameter("verified");                
            String available = request.getParameter("available");                
            String posted = request.getParameter("posted");    
            
            String postDate = request.getParameter("postDate");   
            String expiryDate = request.getParameter("expiryDate");  
            String dateCreated = request.getParameter("dateCreated");           
            String creatorID = request.getParameter("creatorID");  
            
            ServiceResponse<Listing> response1 = listingService.read(id);              
            Listing listing = response1.getResponse();          
            
            if (listing != null) {
                listing.setLeaseLongTerm(StringUtils.isEmpty(leaseLongTerm) ? false : true);
                listing.setLeaseShortTerm(StringUtils.isEmpty(leaseShortTerm) ? false : true);

                listing.setLongMonthRate(longMonthRate);            
                listing.setShortDayRate(shortDayRate);
                listing.setShortWeekRate(shortWeekRate);
                listing.setShortMonthRate(shortMonthRate);
                                
                listing.setLongMonthRateNum(RateUtils.strRateToNum(longMonthRate));
                listing.setShortMonthRateNum(RateUtils.strRateToNum(shortMonthRate));
                listing.setShortWeekRateNum(RateUtils.strRateToNum(shortWeekRate));
                listing.setShortDayRateNum(RateUtils.strRateToNum(shortDayRate));
            
                listing.setPropertyTypeID(propertyTypeID);
                listing.setStatusTypeID(statusTypeID);
                listing.setPosterTypeID(posterTypeID);
                listing.setFurnishTypeID(furnishTypeID);
                
                listing.setTitle(title);
                listing.setDescription(StringUtils.isEmpty(description) ? "" : description.trim());
                listing.setNotes(notes);

                listing.setAddress(address);

                listing.setCountry(country);
                listing.setRegion(region);
                listing.setCity(city);
                listing.setBarangay(barangay);
                listing.setStreet(street);
                listing.setStructure(structure);
                listing.setNumber(number);
                listing.setFloor(floor);
                listing.setZip(zip);            
                listing.setLat(lat);
                listing.setLng(lng);

                listing.setSqArea(StringUtils.isEmpty(sqArea) ? 0 : Double.parseDouble(sqArea));
                listing.setNumBedrooms(StringUtils.isEmpty(numBedrooms) ? 0 : Integer.parseInt(numBedrooms) );
                listing.setNumBathrooms(StringUtils.isEmpty(numBathrooms) ? 0 : Integer.parseInt(numBathrooms) );
                listing.setAmenityIDs(StringUtils.isEmpty(amenityIDs) ? null : Arrays.asList(amenityIDs.split("\\s*,\\s*")));

                listing.setMonthRate(monthRate);
                listing.setSellingPrice(sellingPrice);
                
                listing.setAvailabilityDate(StringUtils.isEmpty(availabilityDate) ? null : CXDateUtils.parseSDF1(availabilityDate));  

                listing.setPlaceIDs(StringUtils.isEmpty(placeIDs) ? null : Arrays.asList(placeIDs.split("\\s*,\\s*")));

                listing.setVerified(StringUtils.isEmpty(verified) ? false : true);
                listing.setAvailable(StringUtils.isEmpty(available) ? false : true);
                listing.setPosted(StringUtils.isEmpty(posted) ? false : true);
                
                listing.setPostDate(StringUtils.isEmpty(postDate) ? null : CXDateUtils.parseSDF1(postDate));  
                listing.setExpiryDate(StringUtils.isEmpty(expiryDate) ? null : CXDateUtils.parseSDF1(expiryDate));  
                listing.setDateCreated(StringUtils.isEmpty(dateCreated) ? null : CXDateUtils.parseSDF1(dateCreated)); 
                listing.setCreatorID(creatorID); 
                
                
                ServiceResponse<Boolean> response = listingService.update(listing);
                map.put("listing", response.getResponse());
                mav.setView(new RedirectView("listing.htm?a="+ListingAction.READ_MANAGE+"&id="+id));
            }
            else {
                mav.setView(new RedirectView("listing.htm?a="+ListingAction.READ_ALL_MANAGE));                
            }
        }        
        else {   
            String id = request.getParameter("id");
            ServiceResponse<Listing> response1 = listingService.read(id); 
            ServiceResponse<List<Place>> response2 = placeService.readAll(0, 0);
            ServiceResponse<List<Amenity>> response3 = amenityService.readAll(0, 0);
            
            map.put("listing", response1.getResponse());
            map.put("places", response2.getResponse());
            map.put("amenities", response3.getResponse()); 
            mav.setViewName("listingedit_manage");
        }
    }
    
    private void delete_manage(ModelAndView mav, Map map, HttpServletRequest request) {
        //String id = request.getParameter("id");
        //ServiceResponse<Boolean> response = listingService.delete(id);        
        mav.setView(new RedirectView("listing.htm?a="+ListingAction.READ_ALL_MANAGE));
    }
    
    
    private void createPhoto_manage(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {        
        Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields");
        List<Photo> photos = new ArrayList<Photo>();
        
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);       
        String listingID = formfields.get("id"); 
        
        try {
            if (isMultipart) {
                List filefields = (List) parameterMap.get("filefields");
                Iterator iterator = filefields.iterator();

                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();

                    if (!item.isFormField()) {
                        String fileName = item.getName();
                        
                        if (!StringUtils.isEmpty(fileName)) {
                            String ext = "";
                            
                            if (StringUtils.containsIgnoreCase(fileName, ".jpg")) {
                                ext = ".jpg";
                            }
                            if (StringUtils.containsIgnoreCase(fileName, ".png")) {
                                ext = ".png";
                            }
                            
                            String genFileName = UUID.randomUUID().toString();                        
                            fileName = genFileName;
                            fileName = fileName + ext;
                            
                            String root = getServletContext().getRealPath("/");
                            root = SystemProperties.PHOTO_DIRECTORY;
                            File path = new File(root);

                            if (!path.exists()) {
                                boolean status = path.mkdirs();
                            }
                            File uploadedFile = new File(path + "/" + fileName );
                                                        
                            if (!uploadedFile.exists()) {
                                //CX: write photo
                                item.write(uploadedFile);
                                //CX: write standard and preview sizes
                                ImageProcessor proc = new ImageProcessor();
                                proc.createStandardSize(uploadedFile);
                                proc.createPreviewSize(uploadedFile);
                            }
                            photos.add(new Photo(root, fileName));
                        }
                    }
                }
            }

            if (formfields != null && !StringUtils.isEmpty((String) formfields.get("s"))) {                
                if (photos != null && photos.size() > 0) {
                    for (Photo photo : photos) {
                        ServiceResponse<String> response1 = photoService.createListingPhoto(listingID, photo);  
                        Thread.sleep(1100);                      
                    }                    
                }
            }            
        } 
        catch (Exception ex) {
            ex.printStackTrace();
        }        
        
        mav.setView(new RedirectView("listing.htm?a="+ListingAction.UPDATE_PHOTO_MANAGE+"&id="+listingID));   
    }   
    
    private void deletePhoto_manage(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {        
        String listingID = request.getParameter("listingID");
        String photoID = request.getParameter("photoID");
        ServiceResponse<Boolean> response = photoService.deleteListingPhoto(listingID, photoID);  
        mav.setView(new RedirectView("listing.htm?a="+ListingAction.UPDATE_PHOTO_MANAGE+"&id="+listingID));
    }
        
    private void updatePhoto(String userID, ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {        
        String id = request.getParameter("id");
        String photoID = request.getParameter("photoID");        
        ServiceResponse<Listing> response1 = listingService.read(id); 
        
        Listing listing = response1.getResponse();
        if (listing != null && StringUtils.equalsIgnoreCase(listing.getCreatorID(), userID)) {
            map.put("listing", response1.getResponse());
            if (isThisRequestCommingFromAMobileDevice(request)) {
                mav.setViewName("listingeditphoto_mobile");                
            }
            else {
                mav.setViewName("listingeditphoto");
            }           
        }
        else {
            mav.setView(new RedirectView("home.htm"));
        }
    }
    
    private void updatePhoto_manage(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {
        String id = request.getParameter("id");
        String photoID = request.getParameter("photoID");        
        ServiceResponse<Listing> response1 = listingService.read(id); 
        
        map.put("listing", response1.getResponse());
        mav.setViewName("listingeditphoto_manage");
    }
    
    private void setListingAvailable(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {        
        String listingID = request.getParameter("id");
        ServiceResponse<Boolean> response1 = listingService.setAvailability(listingID, true);
        ServiceResponse<Boolean> response2 = listingService.postListing(listingID);
        mav.setView(new RedirectView("account.htm"));
    }
    
    private void setListingUnavailable(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {        
        String listingID = request.getParameter("id");
        ServiceResponse<Boolean> response = listingService.setAvailability(listingID, false);
        mav.setView(new RedirectView("account.htm"));
    }
    
    private void setListingAvailableLink(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {        
        String listingID = request.getParameter("id");
        ServiceResponse<Boolean> response1 = listingService.setAvailability(listingID, true);
        ServiceResponse<Boolean> response2 = listingService.postListing(listingID);
        ServiceResponse<Listing> response3 = listingService.read(listingID);
        
        map.put("listing", response3.getResponse());
        map.put("availability", 1);
        
        if (isThisRequestCommingFromAMobileDevice(request)) {
            mav.setViewName("listingsuccess_availability_mobile");
        }
        else {
           mav.setViewName("listingsuccess_availability"); 
        }        
    }
    
    private void setListingUnavailableLink(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {        
        String listingID = request.getParameter("id");
        ServiceResponse<Boolean> response = listingService.setAvailability(listingID, false);
        map.put("availability", 2);
        
        if (isThisRequestCommingFromAMobileDevice(request)) {
            mav.setViewName("listingsuccess_availability_mobile");
        }
        else {
           mav.setViewName("listingsuccess_availability"); 
        } 
    }
    
    private void postListing(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {        
        String listingID = request.getParameter("id");
        ServiceResponse<Boolean> response = listingService.postListing(listingID);
        mav.setView(new RedirectView("account.htm"));
    }
    
    private void unpostListing(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {        
        String listingID = request.getParameter("id");
        ServiceResponse<Boolean> response = listingService.unpostListing(listingID);
        mav.setView(new RedirectView("account.htm"));
    }
    
    private void penalizeListing(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {        
        String listingID = request.getParameter("id");
        String strPenalize = request.getParameter("penalize");
        ServiceResponse<Boolean> response = listingService.setPenalized(listingID, StringUtils.equalsIgnoreCase(strPenalize, "1") ? true : false);
        mav.setView(new RedirectView("listing.htm?a=9001"));
    }
    
    private void shareListing(ModelAndView mav, Map map, HttpServletRequest request) {
        String listingID = request.getParameter("id");
        ServiceResponse<Listing> response = listingService.read(listingID);
        map.put("listing", response.getResponse());
        if (isThisRequestCommingFromAMobileDevice(request)) {
            mav.setViewName("listing_share_mobile");            
        }
        else {            
            mav.setViewName("listing_share");
        }        
    }    
    
    private void mapListing(ModelAndView mav, Map map, HttpServletRequest request) {
        
        if (!StringUtils.isEmpty(request.getParameter("s"))) {
            String listingID = request.getParameter("id");
            String lat = request.getParameter("lat");
            String lng = request.getParameter("lng");
                        
            ServiceResponse<Listing> response1 = listingService.read(listingID);              
            Listing listing = response1.getResponse();          
            
            if (listing != null) {
                listing.setLat(lat);
                listing.setLng(lng);
                listingService.update(listing);
            }
            mav.setView(new RedirectView("listing.htm?a=11000&id=" + listingID));            
        }
        else {
            String listingID = request.getParameter("id");
            ServiceResponse<Listing> response = listingService.read(listingID);
            map.put("listing", response.getResponse());
            mav.setViewName("listingeditlocation");            
        }
    }
    
    private void emalListingApproved(ModelAndView mav, Map map, HttpServletRequest request) {
        String listingID = request.getParameter("id");
        String listingTitle = "";
        String ownerEmail = "";
        String ownerName = "";
        
        ServiceResponse<Listing> response = this.listingService.read(listingID);
        Listing listing = response.getResponse();
        
        if (listing != null) {
            ServiceResponse<User> response1 = userService.read(listing.getCreatorID());
            listingTitle = listing.getTitle();
                        
            User user = response1.getResponse();
            if (user != null) {
                ownerEmail = user.getEmail();
                ownerName = user.getFirstName();
                
                emailService.sendPostListingApproved(listingTitle, ownerName, ownerEmail);
            }
        }
        mav.setView(new RedirectView("listing.htm?a=9001"));
    }
    
    private void emalListingRejected(ModelAndView mav, Map map, HttpServletRequest request) {
        String listingID = request.getParameter("id");
        String listingTitle = "";
        String ownerEmail = "";
        String ownerName = "";
        
        ServiceResponse<Listing> response = this.listingService.read(listingID);
        Listing listing = response.getResponse();
        
        if (listing != null) {
            ServiceResponse<User> response1 = userService.read(listing.getCreatorID());
            listingTitle = listing.getTitle();
                        
            User user = response1.getResponse();
            if (user != null) {
                ownerEmail = user.getEmail();
                ownerName = user.getFirstName();
                
                emailService.sendPostListingRejected(listingTitle, ownerName, ownerEmail);
            }
        }
        mav.setView(new RedirectView("listing.htm?a=9001"));
    }
        
    private void emalListingFeatured(ModelAndView mav, Map map, HttpServletRequest request) {
        String listingID = request.getParameter("id");
        String listingTitle = "";
        String ownerEmail = "";
        String ownerName = "";
        
        ServiceResponse<Listing> response = this.listingService.read(listingID);
        Listing listing = response.getResponse();
        
        if (listing != null) {
            ServiceResponse<User> response1 = userService.read(listing.getCreatorID());
            listingTitle = listing.getTitle();
                        
            User user = response1.getResponse();
            if (user != null) {
                ownerEmail = user.getEmail();
                ownerName = user.getFirstName();
                
                emailService.sendListingFeatured(listingTitle, ownerName, ownerEmail);
            }
        }
        mav.setView(new RedirectView("listing.htm?a=9001"));
    }
        
    private void emalListingBoost(ModelAndView mav, Map map, HttpServletRequest request) {
        String listingID = request.getParameter("id");
        String listingTitle = "";
        String ownerEmail = "";
        String ownerName = "";
        
        ServiceResponse<Listing> response = this.listingService.read(listingID);
        Listing listing = response.getResponse();
        
        if (listing != null) {
            ServiceResponse<User> response1 = userService.read(listing.getCreatorID());
            listingTitle = listing.getTitle();
                        
            User user = response1.getResponse();
            if (user != null) {
                ownerEmail = user.getEmail();
                ownerName = user.getFirstName();
                
                emailService.sendListingBoost(listingID, listingTitle, ownerName, ownerEmail);
            }
        }
        mav.setView(new RedirectView("listing.htm?a=9001"));
    }
    
    
    private void emalListingEnded(ModelAndView mav, Map map, HttpServletRequest request) {
        String listingID = request.getParameter("id");
        String listingTitle = "";
        String ownerEmail = "";
        String ownerName = "";
        
        ServiceResponse<Listing> response = this.listingService.read(listingID);
        Listing listing = response.getResponse();
        
        if (listing != null) {
            ServiceResponse<User> response1 = userService.read(listing.getCreatorID());
            listingTitle = listing.getTitle();
                        
            User user = response1.getResponse();
            if (user != null) {
                ownerEmail = user.getEmail();
                ownerName = user.getFirstName();
                
                emailService.sendPropertyFeaturedExpired(listingTitle, ownerName, ownerEmail);
            }
        }
        mav.setView(new RedirectView("listing.htm?a=9001"));
    }
    
    private void populateListingPlaces(Listing listing) {
        Place matchedPlace = null;
        if (matchedPlace == null) {
            ServiceResponse<Place> response1 = placeService.readClosestMatch(KPlaceTypeIDs.BUILDING, listing.getStructure());
            matchedPlace = response1.getResponse();
        }
        if (matchedPlace == null) {
            ServiceResponse<Place> response2 = placeService.readClosestMatch(KPlaceTypeIDs.VILLAGE, listing.getStructure());
            matchedPlace = response2.getResponse();
        }

        if (matchedPlace != null) {
            if (listing.getPlaceIDs() == null) {
                listing.setPlaceIDs( new ArrayList<String>() );
            }
            listing.getPlaceIDs().add(matchedPlace.getId());
            listing.setLat(matchedPlace.getLat());
            listing.setLng(matchedPlace.getLng());

            //CX: try to get district
            if (matchedPlace.getDistrictIDs() != null && matchedPlace.getDistrictIDs().size() > 0) {
                for (String districtID : matchedPlace.getDistrictIDs()) {
                    ServiceResponse<Place> response3 = placeService.read(districtID);
                    Place district = response3.getResponse();
                    if (district != null) {
                        listing.getPlaceIDs().add(district.getId());
                    }
                }
            }
        }
    }
              
    private Listing fixListingData(Listing listing) {
        Listing trimmed = listing;
        try {
            if (trimmed != null) {        
                trimmed.setId(listing.getId());
                trimmed.setTitle(listing.getTitle());
                trimmed.setDisplayTitle(listing.getDisplayTitle());
                trimmed.setUrlTitle(listing.getUrlTitle());
                trimmed.setAddress(listing.getAddress());
                trimmed.setPrimaryPhoto(listing.getPrimaryPhoto());
                trimmed.setSqArea(listing.getSqArea());
                trimmed.setLongMonthRate(String.format("%,.0f", listing.getLongMonthRateNum()));
                trimmed.setShortDayRate(String.format("%,.0f", listing.getShortDayRateNum()));
                trimmed.setShortWeekRate(String.format("%,.0f", listing.getShortWeekRateNum()));
                trimmed.setShortMonthRate(String.format("%,.0f", listing.getShortMonthRateNum()));
                trimmed.setAvailable(listing.isAvailable());
                trimmed.setLeaseLongTerm(listing.isLeaseLongTerm());
                trimmed.setLeaseShortTerm(listing.isLeaseShortTerm());
                trimmed.setCommunity(listing.getCommunity());
                trimmed.setCity(listing.getCity());     
            }       
        }
        catch (Exception ex) {
            trimmed = listing;
            ex.printStackTrace();
        }
        return trimmed;
    }
    
    
    public static void main (String[] argv) {
        IFeaturedService featuredService = new DFeaturedService();
        ServiceResponse<List<Featured>> response1 = featuredService.randomFeatured("makati", "1", 3);
        List<Featured> featureds = response1.getResponse();
        
        for (Featured featured : featureds) {
            System.out.println("CX: " + featured.getListingID());
        }
    }
    
}
